<?php

/**
 * Account class represents an account 
 */
class Account extends Model {

	public $id;
	public $password;
	public $startdate;
	public $enddate;
	
	/**
	 * constructs parent
	 */
	function __construct() {
		parent::__contruct();
	}	
	
	/** 
	 * Gets an Account object
	 * @param account_id The id of the account
	 * @return Account 
	 */	
	function get($account_id) {	
		$sth = $this->db->prepare('SELECT * FROM account
								   WHERE id = :account_id');
		$sth->setFetchMode(PDO::FETCH_INTO, $this);	
		$sth->execute(array('account_id' => $account_id));
		return $sth->fetch();			
	}
	
	/**  
	 * Gets an account object by chip_id
	 * @param chip_id The chip_id of an user
	 * @return account 
	 */		
	function getAccountByChipId($chip_id) {
		$sth = $this->db->prepare('SELECT a.* FROM account a
								   LEFT JOIN account_chip ac ON ac.account_id = a.id
								   LEFT JOIN chip c ON c.id = ac.chip_id								   
								   WHERE ac.chip_id = :chip_id');
		$sth->setFetchMode(PDO::FETCH_INTO, $this);	
		$sth->execute(array('chip_id' => $chip_id));
		return $sth->fetch(PDO::FETCH_OBJ);			
	}
	
	/**  
	 * Gets an account and check if it is a valid user
	 * @param chip_id The chip_id of an user
	 * @return account 
	 */		
	function isValidUser($chip_id){
		$sth = $this->db->prepare('SELECT a.id, ac.chip_id FROM account a
								   LEFT JOIN account_chip ac ON ac.account_id = a.id
								   LEFT JOIN chip c ON c.id = ac.chip_id								   
								   WHERE c.id = :chip_id');
		$sth->execute(array('chip_id' => $chip_id));
		$account = $sth->fetch(PDO::FETCH_OBJ);
		
		return $account;
	}
	
	/**  
	 * Save's an account object
	 * @return true if saved succesfully else return false 
	 */			
	function save() {
		if($this->id) {
			if($this->db->update('account', $this)) {
				return true;
			};
		} else {
			if($this->db->insert('account', $this)) {
				return true;
			};
		}
		return false;
	}
}